package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSONObject;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.IPUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.transaction.api.TransactionService;
import com.huiminpay.transaction.api.dto.PayOrderDTO;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
@Slf4j
@Controller
public class PayController {

    @Reference
    TransactionService transactionService;

    @Reference
    AppService appService;

    @RequestMapping(value = "/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request){

        //组装获取参数
        //解码  json
        String stringBase64 = EncryptUtil.decodeUTF8StringBase64(ticket);
        //转对象
        PayOrderDTO payOrderDTO = JSONObject.parseObject(stringBase64, PayOrderDTO.class);
        String params = null;
        try {
            // 拼的参数
            // merchantId=23413&appId=dgkrkly&storeId=6536&subject=kjsdfla&body=jldafjl
            params = ParseURLPairUtil.parseURLPair(payOrderDTO);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //判断扫码的服务类型
//        String userAgent = request.getHeader("User-Agent");
        String header = request.getHeader("User-Agent");
        BrowserType type = BrowserType.valueOfUserAgent(header);
        //判断
        switch(type){
            case ALIPAY:
                return "forward:/pay‐page?" + params;
            case WECHAT:
                return "forward:/pay‐page?" + params;
            default:
                return "pay_error";
        }
    }

    @ApiOperation("支付宝门店下单付款")
    @PostMapping("/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO orderConfirmVO,
                                          HttpServletRequest request,
                                          HttpServletResponse response){
        //保存订单  &   请求交易服务的对接支付宝接口
        // vo转dto
        PayOrderDTO payOrderDTO = PayOrderConvert.INSTANCE.vo2Dto(orderConfirmVO);
        AppDTO appDTO = appService.queryAppDetail(orderConfirmVO.getAppId());
        Long merchantId = appDTO.getMerchantId();
        payOrderDTO.setMerchantId(merchantId);
        payOrderDTO.setClientIp(IPUtil.getIpAddr(request));
        PaymentResponseDTO<String> responseDTO = transactionService.submitOrderByAli(payOrderDTO);
        // 阿里返回的支付表单
        String form = responseDTO.getContent();
        try {
            //处理数据   将支付宝响应的表单页面回写到客户端
            response.setContentType("text/html;charset=utf-8");
            // 直接将完整的表单html输出到页面
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
